'''
Function:
    解析game中的所有元素信息
author:
    walker
time:
    2020/5/14
'''
from config import *

class Game_parse():
    def __init__(self):
        self.info = 'game parser'

    '''读取txt文件'''
    def read_txt(self,level_path):
        content_list = []
        with open(level_path,'r') as f:
            # 按行读取文件,读取出来是list，list中每行是str
            level_str_list = f.read().splitlines()
        f.close()
        print("### Config ###")
        for level_str_list_item in level_str_list:
            print(level_str_list_item)
        print("")
        return level_str_list

    '''统计list中每个元素出现的个数，过程是由list转为dict'''
    def count_list_role(self,arr):
        result = {}
        for i in set(arr):
            result[i] = arr.count(i)
        return result

    def parse_list_to_str(self,grid_list_list):
        grid_list_str = []
        for content in grid_list_list:
            grid_list_str.append(''.join(content))
        return grid_list_str


    '''将grid（地图）从list中包含str变为list中包含list的格式'''
    def parse_str_to_list(self,grid_list_str):
        #地图list
        grid_list_list = []
        #用于检测地图中是否存在有违规的字母
        value_error_list = []
        for content in grid_list_str:
            list = []
            for content_item in content:
                list.append(content_item)
                value_error_list.append(content_item)
            grid_list_list.append(list)

        #将地图从str转为list的结果返回
        return grid_list_list,value_error_list

    '''检测地图是否存在错误'''
    def value_error_input(self,value_error_list):
        #将输入的list转为dict
        count_list_role_dic = self.count_list_role(value_error_list)

        key_list = []
        value_list = []
        for key,value in count_list_role_dic.items():
            #如果地图中是否存在未知的字母，则直接返回错误
            if key not in ROLE_LIST:
                print("The levels contains an unknown letter:",key)
                raise ValueError("Bad letter in configuration file: <letter>.")
            #如果传送模块不是成对出现的，则返回错误
            elif key == '1' or key == '2' or key =='3' or key =='4' or key =='5' or key =='6' or key =='7' or key =='8' or key =='9':
                if value != 2:
                    print("The error teleport pads is:",key)
                    raise ValueError("Teleport pad <number> does not have an exclusively matching pad.")
            #起始点和终点只能为一个
            elif key == 'X' or key =='Y':
                if value != 1:
                    print("There can only be one starting point or one ending point:",key)
                    raise ValueError("Expected 1 starting position, got <number>.")
